import {
	baseUrl,
	prefix,
} from '@/config';

import {
	useAppStore
} from '@/store';

const appStore = useAppStore();


const request = (url = '', data = {}, type = 'GET', header = {
	terminal: 'WECHAT'
}) => {
	const token = uni.getStorageSync('token');
	if (token) {
		header['token'] = token;
	}
	return new Promise((resolve, reject) => {
		uni.request({
			method: type,
			url: baseUrl + prefix + url,
			data: data,
			header: header,
			dataType: 'json',
		}).then((res) => {
			if (res.data.code == 200) {
				resolve(res.data);
			} else {
				if (res.data.code == 5000000) {
					appStore.OPEN_LOGIN_POPUP(); // 打开登录弹框
					// uni.navigateTo({
					// 	url: "/pages/login/login"
					// })
					uni.removeStorageSync('token');
					uni.removeStorageSync('userInfo');
					return;
				} else { // 非 未登录 则弹出错误提示
					uni.showToast({
						title: res.data.msg,
						duration: 2000,
						icon: 'none'
					});
					setTimeout(() => {
						// 平台禁用用户后-跳转登录页
						if (res.data.code == 5000007) {
							uni.navigateTo({
								url: "/pages/login/login"
							})
							uni.removeStorageSync('token');
							uni.removeStorageSync('userInfo');
						}
					}, 2000)
				}

				resolve({
					data: null
				})

			}
		}).catch(error => {
			console.log('error', error);
			let [err, res] = error;
			reject(err)
		})
	});
}


const upload = (url, file, otherData = {}) => {
	const token = uni.getStorageSync('token');
	let header = {}
	if (token) {
		header['token'] = token;
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseUrl + prefix + url,
			filePath: file,
			name: 'file',
			header: header,
			formData: {
				'file': file,
				...otherData
			},
			success: (res) => {
				console.log('file', res);
				if (res.data) {
					const data = JSON.parse(res.data);
					if (data.code == 200) {
						resolve(data.data);
					}
				}
			},

		})
	});


}
export {
	upload
}
export default request